package com.fyb.basic.juc.masterWork;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.function.Consumer;

/**
 * Master 负责接收客户端提交的任务，然后通过阻塞队列对任务进行缓存。
 * Master 所拥有的线程作为阻塞队列的消费者，不断从阻塞队列获取任务并轮流分给 Worker。
 */
public class Master<T extends Task<R>, R> {
    /**
     * 封装工作线程的集合
     */
    private final Map<String, Worker<R>> workerMap = new HashMap<>();
    /**
     * 基于数组的阻塞队列
     */
    private final ArrayBlockingQueue<Task<R>> taskQueue = new ArrayBlockingQueue<>(1024);

    /**
     * 主线程
     */
    private Thread masterThread = null;

    /**
     * @param workCount 工作线程数
     */
    public Master(int workCount) {
        for (int i = 0; i < workCount; i++) {
            Worker<R> worker = new Worker<>();
            workerMap.put(String.format("%s-%s", "worker", i), worker);
        }
        masterThread = new Thread(this::execute);
        masterThread.start();
        System.out.println("Master 模式启动。。。。。");
    }

    private void execute() {
        while (true) {
            workerMap.forEach((workerName, worker) -> {
                try {
                    Task<R> task = this.taskQueue.take();
                    worker.submit(task);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
    }

    public void submit(T task, Consumer<R> resultAction) {
        // 设置任务回调
        task.setResultAction(resultAction);
        taskQueue.add(task);
    }

}
